package com.tg.appcommon.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import com.tange.base.toolkit.NetworkType;
import com.tange.base.toolkit.NetworkUtil;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.listener.NetStateChangeObserver;

import java.util.ArrayList;
import java.util.List;


public class NetStateChangeReceiver extends BroadcastReceiver {
    private NetworkType mType = NetworkUtil.getNetworkType(TGApplicationBase.getApplication());
    private List<NetStateChangeObserver> mObservers = new ArrayList<>();
    private  Context  context;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())){
            NetworkType networkType = NetworkUtil.getNetworkType(context);
            notifyObservers(networkType);
        }
    }

    public  void registerReceiver(Context context){
        this.context = context;
        IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver( this,intentFilter);
    }

    public  void unRegisterReceiver(){
        context.unregisterReceiver(this);
    }

    public  void registerObserver(NetStateChangeObserver observer){
        if (observer == null) {
            return;
        }
        if (!mObservers.contains(observer)){
            mObservers.add(observer);
        }
    }

    public  void unRegisterObserver(NetStateChangeObserver observer){
        if (observer == null) {
            return;
        }
        if (mObservers == null) {
            return;
        }
        mObservers.remove(observer);
    }

    private void notifyObservers(NetworkType networkType){
        if (mType == networkType) {
            return;
        }
        mType = networkType;
        if (networkType == NetworkType.NETWORK_NO){
            for (NetStateChangeObserver observer : mObservers){
                observer.onNetDisconnected();
            }
        }else {
            for (NetStateChangeObserver observer : mObservers){
                observer.onNetConnected(networkType);
            }
        }
    }
}
